package com.ustc.hewei.consumerweb.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ustc.hewei.commonmodule.dto.UserDTO;
import com.ustc.hewei.consumerweb.utils.Constants;
import com.ustc.hewei.consumerweb.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ustc.hewei.consumerweb.utils.Constants.LOGIN_USER_KEY;
import static com.ustc.hewei.consumerweb.utils.Constants.LOGIN_USER_TTL;

/**
* @description: TODO
* @author hewei
* @date 2022/10/5 20:37
* @version 1.0
*/

public class FirstLoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public  FirstLoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (StrUtil.isBlank(token)) {
            return true;
        }
        Map<Object, Object> userEntry = stringRedisTemplate.opsForHash().entries(LOGIN_USER_KEY + token);
        if (userEntry.isEmpty()) {
            return true;
        }
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userEntry, new UserDTO(), false);
        UserHolder.saveUser(userDTO);
        // 用户每操作一次就更新一次时间，不用重复登录，用户长时间不操作就自动退出登陆
        stringRedisTemplate.expire(LOGIN_USER_KEY + token, LOGIN_USER_TTL,TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
